<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="Spu名称">
        <el-input placeholder="请输入Spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm, index) in tradeMarkList" :key="tm.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input placeholder="Spu描述" type="textarea" rows="4" v-model="spu.description"></el-input>
      </el-form-item>
      <!-- //上传一张用组件upload  多张用照片墙也是组件upload  -->
      <el-form-item label="SPU图片">
        <!-- 上传图片 action 上传地址-->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handlSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}未选择`" v-model="attrIdAndAttrName">
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="(unselect, index) in unSelectSaleAttr"
            :key="unselect.id"
          >
          </el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center"> </el-table-column>
          <el-table-column prop="saleAttrName" label="属性值" width="width"> </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- 切换 -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              >
                <!-- @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm" -->
              </el-input>
              <!-- @click="showInput" -->
              <el-button v-else class="button-new-tag" size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">报存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      //spu属性
      spu: {
        category3Id: 0,
        tmId: '', //品牌id
        description: '', //描述
        spuName: '', //spu名称
        //收集图片

        spuImageList: [
          // {
          //   id: 0,
          //   imgName: 'string',
          //   imgUrl: 'string',
          //   spuId: 0,
          // },
        ],
        // 平台属性
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: 'string',
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: 'string',
          //       saleAttrName: 'string',
          //       saleAttrValueName: 'string',
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      tradeMarkList: [], //品牌名信息
      spuImageList: [], //图片
      saleAttrList: [], //销售属性列表
      attrIdAndAttrName: '', //未选择属性的id
    }
  },
  methods: {
    handleRemove(file, fileList) {
      //file删除的。fileList剩余的
      // console.log(file, fileList)
      this.spuImageList = fileList //有name和url 所以提交服务器的时候需要处理
    },
    //照片墙图片预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //初始化spuForm数据
    async initSpuData(spu) {
      // 获取某一个spu数据信息 先拿到id
      let spuResult = await this.$API.spu.reqSpu(spu.id)
      console.log(spuResult)
      if (spuResult.code == 200) {
        this.spu = spuResult.data
      }
      // console.log(spu.id)
      // console.log(spu)
      //获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList()
      console.log(tradeMarkResult)
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      //获取图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id)
      console.log(spuImageResult)
      if (spuImageResult.code == 200) {
        let lisAtrr = spuImageResult.data
        //由于照片墙需要的是数组  而且需要 name  url 两个属性
        lisAtrr.forEach((item) => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = lisAtrr
      }

      //获取平台销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      console.log(saleResult)
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }
    },
    //图片上传成功
    handlSuccess(response, file, fileList) {
      //response 这张图片上传成功服务器返回的真是的信息
      this.spuImageList = fileList
    },
    //收集到添加属性的信息 然后。。
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(':')
      //给spu 方便符合服务器的模板
      let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      this.attrIdAndAttrName = ''
    },
    //添加按钮回调
    addSaleAttrValue(row) {
      // console.log(row)
      this.$set(row, 'inputVisible', true)
      this.$set(row, 'inputValue', '')
    },
    // input失去焦点回调、
    handleInputConfirm(row) {
      ///显示销售属性当前收集的值
      // console.log(row)
      const { baseSaleAttrId, inputValue } = row
      //新增不能为空
      if (inputValue.trim() == '') {
        this.$message('输入不能为空')
        return
      }
      //不重复
      let result = row.spuSaleAttrValueList.every((item) => item.saleAttrValueName != inputValue)
      if (!result) return

      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(newSaleAttrValue)
      //  显示button

      row.inputVisible = false
    },
    //保存按钮回调
    async addOrUpdateSpu() {
      //先整理参数
      //图片需要改为imageName和imageUrl
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        }
      })
      //发请求保存
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      console.log(result)

      if (result.code == 200) {
        this.$message({ type: 'success', message: '保存成功' })
        this.$emit('changeScene', { scene: 0, flag: this.spu.id ? '修改' : '添加' }) //切换页面  应改到下边if 里面 这里不成功位演示
      }
    },
    //按添加spu zi'zu子组件发两个请求
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id
      //获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList()
      console.log(tradeMarkResult)
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      //获取平台销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      console.log(saleResult)
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }
    },
    //取消
    cancel() {
      this.$emit('changeScene', { scene: 0, flag: '' })
      //取消这时再次进来页面 还有数据 需要清空数据
      object.assign(this._data, this.$options.data()) //新方法哈哈
    },
  },
  computed: {
    //计算未选择的属性数量
    unSelectSaleAttr() {
      let result = this.saleAttrList.filter((item) => {
        // console.log(item)
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName
        })
      })
      return result
    },
  },
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
